import { Context, Next } from 'koa'
import { IPayLoad } from '../../utils/password'
import { CommonSecret } from '../../config/secret'
import jwt from 'jsonwebtoken'
import { whiteList } from '../../config'

const permission = async (ctx: Context, next: Next) => {
  const { headers, method, url } = ctx

  ctx.set('Access-Control-Allow-Origin', '*')
  if (method === 'OPTIONS') {
    ctx.set('Access-Control-Allow-Methods', 'OPTIONS, GET, PUT, POST, DELETE')
    ctx.set(
      'Access-Control-Allow-Headers',
      'x-requested-with, accept, origin, content-type, token',
    )
    ctx.set('Content-Type', 'application/json;charset=utf-8')
    ctx.set('Access-Control-Allow-Credentials', 'true')
    ctx.body = ''
    ctx.status = 200
  } else {
    if (!whiteList.includes(url)) {
      const token = headers['token'] as string
      if (token) {
        // 验证时间
        const validation = await new Promise((resolve) => {
          jwt.verify(token, CommonSecret, (_error, res) => {
            if (res) {
              // 验证用户合法性
              const { id } = jwt.decode(token) as IPayLoad
              if (id) {
                ctx.user_id = id
                resolve(true)
              } else resolve(false)
            }
          })
        })
        validation && (await next())
      }
    } else await next()
  }
}

export default permission
